var express = require('express');
var router = express.Router();
var app = require('../app');

router.all('/add', function(req, res) {
    var msg = req.body;
    var time = parseInt(msg.time);
    var url = msg.url;
    var token = req.model.auth.token;

    if(!isNaN(time) && time > 0 && (url != null) && token != null) {
        req.pool.acquire(function(err, conn) {
            conn.call('timers.addRecord', { url_: url, token_: token, time_: time }, function(err, result) {
                req.pool.release(conn);
                res.send(200, "ok");
            });
        });
    } else {
        res.send(200, "ok");
    }
});

router.get('/get', function(req, res) {
    var token = req.model.auth.token;
    if(token != null) {
        req.pool.acquire(function(err, conn) {
            conn.lcall('timers.getStats', { token_: token}, function(err, result) {
                req.pool.release(conn);
                req.model.results = result;
                res.render('report', req.model);
            });
        });
    } else {
        req.model.results = [];
    }
});

module.exports = router;